package cn.lh.pet.service.impl;

import cn.lh.pet.domain.PetType;
import cn.lh.pet.mapper.PetTypeMapper;
import cn.lh.pet.service.IPetTypeService;
import cn.lh.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * 业务实现类：
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {
    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> getPetTypeTree() {
        List<PetType> petTypes = petTypeMapper.loadAll();
        Map<Long, PetType> map = petTypes.stream().collect(Collectors.toMap(PetType::getId, petType -> petType));
        ArrayList<PetType> petTypeTree = new ArrayList<>();
        petTypes.forEach(new Consumer<PetType>() {
            @Override
            public void accept(PetType petType) {
                Long pid = petType.getPid();
                if (pid == null) {
                    petTypeTree.add(petType);
                } else {
                    PetType parent = map.get(pid);
                    parent.getChildren().add(petType);
                }
            }
        });
        return petTypeTree;
    }
}
